package com.kukudb.captcharepeater.filter;

import com.kukudb.captcharepeater.pojo.ResponseMessage;
import com.kukudb.captcharepeater.utils.JWTUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
@WebFilter(urlPatterns = {"/api/admin/*"})
public class IsLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ip = request.getRemoteAddr();
        log.info("IsLoginFilter: " + ip);
        String token = (String) request.getSession().getAttribute("token");
        if (token == null) {
            log.info("用户未登录");
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(new ResponseMessage(401, "用户未登录").toJson());
            return;
        } else {
            Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
            log.info("--session token: " + stringObjectMap);
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
